import { upload as toUpload, getFiles, getFile } from '@luzhongk/upload'
import { message } from 'ant-design-vue'

export function startUpload(file, data = {}, onProgress) {
  const fd = new FormData()
  fd.append('file', file)
  Object.keys(data).forEach((key) => {
    fd.append(key, data[key])
  })
  const params = {
    url: 'https://upload.qiniup.com',
    method: 'post',
    data: fd,
    toast: message.warn,
    onProgress,
  }
  return toUpload(params)
}

export async function upload(accept = 'image/*', data, onProgress) {
  const file = await getFile({ accept })
  if (!file) return null
  return startUpload(file, data, onProgress)
}

export async function uploadFiles(accept = 'image/*', data, onProgress) {
  const files = await getFiles({ accept })
  if (!files.length) return null
  const ret = []
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    const res = await startUpload(file, data, onProgress)
    ret.push(res)
  }
  return ret
}
